'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 使用消耗器
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../../../../consts/code');
var PlayerManager = require('../../../../libs/playerManager');
var consumeType = require('../../../../consts/consumeType');
var consumeConf = require('../../../../config/consumeConf');
var buildType = require('../../../../consts/buildType');
var roleService = require('../../../../services/roleService');
var moment = require('moment');
var dataApi = require('../../../../libs/dataApi');
var rewardType = require('../../../../consts/rewardType.js');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var consume_id = msg.consume_id;
    var num = msg.num;
    var build_id = msg.build_id;
    var quick_type = msg.quick_type || 0;
    var reward_list = [];
    var build_list = {};
    var quick_list = {};
    var build_end_time = 0;

    if (!consume_id || !num) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'bag', 'task', 'daily_task', 'achieve', 'pvp', 'build', 'tech', 'smithy', 'unionTask', 'sevenDayActivity'],
                    cb
                );
            },
            function (cb) {
                var bag_model = player_manager.bag;
                var build_model = player_manager.build;
                var tech_model = player_manager.tech;
                var union_task_model = player_manager.unionTask;

                for (var i = 0; i < num; i++) {

                    if (!bag_model.subConsume(consume_id)) {
                        return next(null, {
                            code: Code.BAG_CONSUME_NOT_MORE
                        });
                    }

                    _useConsume(player_manager, consume_id, build_id, quick_type, next);
                }
                build_model.buildConsumeTime(function (value) {
                    if (value.build_id == build_id) {
                        build_end_time = moment(value.end_time).unix();
                    }
                });
                var consume_reward_list = dataApi.consume.findById(consume_id);

                //对类型进行转换返回给客户端
                var reward_type = _resultList(consume_id);
                build_list = player_manager.build.getBuild(build_id) || {};
                reward_list.push({
                    reward: 0,
                    reward_type: reward_type,
                    reward_num: consume_reward_list.value * num,
                    hole_num: 0,
                    reward_value: 0
                });

                if (quick_type == 1) {
                    quick_list = build_model.getBuildSchedule(build_id) || {};
                }
                if (quick_type == 2) {
                    var item = {
                        tech_id: tech_model.up_tech_id,
                        tech_end_time: tech_model.up_tech_end_tm
                    };
                    quick_list = item || {};
                }
                if (quick_type == 3) {
                    quick_list = union_task_model.unionTask_list || {};
                }
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    build_id: build_id,
                    build_end_time: build_end_time,
                    reward_list: reward_list,
                    build_list: build_list,
                    quick_list: quick_list
                }
            });
        }
    );
};

/**
 * 使用消耗品
 */
// jshint maxstatements:50
var _useConsume = function (player_manager, consume_id, build_id, quick_type, next) {
    var consume_type_conf = consumeConf.getConsumeTypeConf(consume_id);

    if (!consume_type_conf) {
        return;
    }

    var consume_value = consume_type_conf.value;
    var consume_type = consume_type_conf.type;
    switch (consume_type) {
    case consumeType.PROTECT:
        {
            _useProtect(player_manager, consume_value, consume_id);
            break;
        }
    case consumeType.GOLD:
        {
            _useGold(player_manager, consume_value, consume_id);
            break;
        }
    case consumeType.FOOD:
        {
            _useFood(player_manager, consume_value, consume_id);
            break;
        }
    case consumeType.CHEST:
        {
            _useChest(player_manager, consume_id, build_id);
            break;
        }
    case consumeType.FARM:
        {
            _useFarm(player_manager, consume_id, build_id);
            break;
        }
    case consumeType.COPY_EXP:
        {
            _useCopyExp(player_manager, consume_value);
            break;
        }
    case consumeType.BATTLE_EXP:
        {
            _useBattleExp(player_manager, consume_value);
            break;
        }
    case consumeType.BUILD_TIME:
        {
            _useBuildTime(player_manager, consume_value, build_id);
            // case consumeType.PRODUCT_SOLDIER_TIME:
            //     {
            //         if (!_useProtectSoldierTime(player_manager, consume_value)) {
            //             return next(null, {
            //                 code: Code.SOLDIER_SCHEDULE_NOT_EXIST
            //             });
            //         }
            break;
        }
    case consumeType.PROSPEROUS_PROTECT:
        {
            // 繁荣度卡
            player_manager.role.setProtectProsperous(consume_value);
            break;
        }
    case consumeType.SOLDIERSOUL:
        {
            // 兵魂卡道具
            _useSoldierSoul(player_manager, consume_value, consume_id);
            break;
        }
    case consumeType.SMITHY_ENERGY:
        {
            // 精力卡
            _useSmithyEnergy(player_manager, consume_value, consume_id);
            break;
        }
    case consumeType.ENERGY:
        {
            // 体力卡
            _useEnergy(player_manager, consume_value, consume_id);
            break;
        }
    case consumeType.BUILD_TIME_QUICK:
        {
            // 建筑加速度卡（减少百分比建筑加速时间）
            _useBuildQuick(player_manager, consume_id);
            break;
        }
    case consumeType.BUILD_CONSUME_QUICK:
        {
            // 队列加速度卡（减少科技或是建筑的队列时间）
            _useBuildConsumeQuick(player_manager, build_id, consume_id, quick_type, consume_value);
            break;
        }
    default:
        {
            console.error('invalid consumeType:', consume_type);
            break;
        }
    }
};

/**
 * 使用建筑加速卡(减少百分比建筑加速时间)
 */
var _useBuildConsumeQuick = function (player_manager, build_id, consume_id, quick_type, consume_value) {
    var build_model = player_manager.build;
    var tech_model = player_manager.tech;
    // var consume_quick_time = consumeConf.getConsumeTypeConf(consume_id).value || 0;

    if (quick_type == 1) {
        //建筑队列加速
        build_model.setBuildSchedule(build_id, consume_value);
    }

    if (quick_type == 2) {
        var tech_id = build_id;
        var tech_end_time = tech_model.up_tech_end_tm;
        tech_model.setUpgradeTime(tech_end_time - consume_value);
    }

    if (quick_type == 3) {
        var union_task_id = build_id;
        var union_task_model = player_manager.unionTask;
        union_task_model.quickTaskConsume(union_task_id, consume_value);
    }
};

/**
 * 使用建筑加速卡(减少百分比建筑加速时间)
 */
var _useBuildQuick = function (player_manager, consume_id) {
    var build_model = player_manager.build;
    build_model.setConsumeTime(consume_id);
};

/**
 * 使用体力卡
 */
var _useEnergy = function (player_manager, consume_value, consume_id) {
    var role_model = player_manager.role;
    roleService.addEnergy(player_manager, moduleType.MDL_BAG, operationType.OPR_BAG_USE_CONSUME, consume_value, consume_id);
};

/**
 * 使用精力卡
 */
var _useSmithyEnergy = function (player_manager, consume_value, consume_id) {
    var role_model = player_manager.role;
    roleService.addSmithyEnergy(player_manager, moduleType.MDL_BAG, operationType.OPR_BAG_USE_CONSUME, consume_value, consume_id);
};

/**
 * 使用保护卡
 */
var _useProtect = function (player_manager, consume_value) {
    var role_model = player_manager.role;
    role_model.addProtectTime(consume_value);
};

/**
 * 使用金币包
 */
var _useGold = function (player_manager, consume_value, consume_id) {
    roleService.addGoldLimit(player_manager, moduleType.MDL_BAG, operationType.OPR_BAG_USE_CONSUME, consume_value, consume_id);
};

/**
 * 使用兵魂卡
 */
var _useSoldierSoul = function (player_manager, consume_value, consume_id) {
    roleService.addSoldierSoul(player_manager, moduleType.MDL_BAG, operationType.OPR_BAG_USE_CONSUME, consume_value, consume_id);
};

/**
 * 使用粮食包
 */
var _useFood = function (player_manager, consume_value, consume_id) {
    roleService.addFoodLimit(player_manager, moduleType.MDL_BAG, operationType.OPR_BAG_USE_CONSUME, consume_value, consume_id);
};

/**
 * 使用金矿增益卡
 */
var _useChest = function (player_manager, consume_id, build_id) {
    var chest_build = player_manager.build.getBuild(build_id);
    chest_build.addChestDoubleGainEndTime(consume_id);
};

/**
 * 使用农田增益卡
 */
var _useFarm = function (player_manager, consume_id, build_id) {
    var farm_build = player_manager.build.getBuild(build_id);
    farm_build.addFarmDoubleGainEndTime(consume_id);
};

/**
 * 使用副本经验双倍卡
 */
var _useCopyExp = function (player_manager, consume_value) {
    var copy_model = player_manager.copy;
    copy_model.addCopyExpNum(consume_value);
};

/**
 * 使用掠夺经验双倍卡
 */
var _useBattleExp = function (player_manager, consume_value) {
    var battle_model = player_manager.battle;
    battle_model.addbattleExpNum(consume_value);
};

/**
 * 使用建筑时间卡
 */
var _useBuildTime = function (player_manager, consume_value, build_id) {
    var build_model = player_manager.build;
    var is_valid = false;
    build_model.buildConsumeTime(function (value) {
        if (value.build_id == build_id && value.end_time > moment()) {
            value.end_time = moment(value.end_time).add(-consume_value, 's');
            is_valid = true;
            return true;
        }
    });
    return is_valid;
};

// /**
//  * 使用造兵加速卡
//  */
// var _useProtectSoldierTime = function (player_manager, consume_value) {
//     var soldier_model = player_manager.solder;
//     if (!soldier_model.getLastChange(consume_value)) {
//         return false;
//     }
//     return true;
// };

var _resultList = function (consume_id) {
    var consume_reward_list = dataApi.consume.findById(consume_id);
    var type = consume_reward_list.type;
    switch (type) {
    case consumeType.PROTECT:
        {
            return rewardType.PROTECT; // 护盾
        }
    case consumeType.GOLD:
        {
            return rewardType.GOLD; // 金币
        }
    case consumeType.FOOD:
        {
            return rewardType.FOOD; // 粮食
        }
    case consumeType.ENERGY:
        {
            return rewardType.ENERGY; // 体力
        }
    case consumeType.SMITHY_ENERGY:
        {
            return rewardType.SMITHY_ENERGY; // 精力
        }
    case consumeType.PROSPEROUS_PROTECT:
        {
            return rewardType.PROSPEROUS; // 繁荣度
        }
    case consumeType.SOLDIERSOUL:
        {
            return rewardType.SOLDIER_SOUL; // 兵魂
        }
    default:
        {
            return 0;
        }
    }
};
